﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.Web.Services.Protocols;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;

namespace Microsoft.IT.Crm.Utility.CrmSolutionManager
{
    public class XrmServiceHelper
    {
        private ServiceInformation ServiceInformation;
        public static IOrganizationService OrganizationService = null;

        public XrmServiceHelper(ServiceInformation serviceInformation)
        {
            ServiceInformation = serviceInformation;

            OrganizationService = GetOrganizationService();
        }

        private IOrganizationService GetOrganizationService()
        {
            try
            {
                ClientCredentials clientCredentials = new ClientCredentials();
                if (!string.IsNullOrEmpty(ServiceInformation.Username))
                    clientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(ServiceInformation.Username, ServiceInformation.Password, ServiceInformation.Domain);
                Uri orgServiceUri = new Uri(String.Format("{0}/{1}/XRMServices/2011/Organization.svc", ServiceInformation.OrganizationServiceUrl, ServiceInformation.OrganizationName));
                OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(orgServiceUri, null, clientCredentials, null);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                return service;
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw ex;
            }
            catch (SoapException ex)
            {
                throw ex;
            }
            catch (Exception ex) { throw ex; }
        }
    }
}
